package com.ruoyi.web.controller.system;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.security.Principal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.service.ISysUserService;

/**
 * CAS认证处理
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/cas")
public class CasController
{
    @Autowired
    private ISysUserService userService;
    
    @Autowired
    private TokenService tokenService;
    
    @Value("${cas.server.url}")
    private String casServerUrl;
    
    /**
     * CAS登录
     */
    @GetMapping("/login")
    public AjaxResult login(HttpServletRequest request, HttpServletResponse response) throws IOException
    {
        // 获取CAS登录用户名
        String username = request.getRemoteUser();
        if (StringUtils.isEmpty(username))
        {
            return AjaxResult.error("CAS认证失败");
        }
        
        // 获取用户信息 - 使用通用方式
        Principal principal = request.getUserPrincipal();
        Map<String, Object> attributes = new HashMap<>();
        
        // 如果是AttributePrincipal类型，则获取属性
        if (principal != null && "org.jasig.cas.client.authentication.AttributePrincipal".equals(principal.getClass().getName())) {
            try {
                // 使用反射获取属性
                Method getAttributesMethod = principal.getClass().getMethod("getAttributes");
                Object result = getAttributesMethod.invoke(principal);
                if (result instanceof Map) {
                    attributes = (Map<String, Object>) result;
                }
            } catch (Exception e) {
                // 忽略异常，继续使用空属性集
            }
        }
        
        // 查询用户信息
        SysUser user = userService.selectUserByUserName(username);
        if (user == null)
        {
            // 如果用户不存在，可以选择自动创建用户
            // 这里简化处理，返回错误信息
            return AjaxResult.error("用户不存在");
        }
        
        // 生成token
        LoginUser loginUser = new LoginUser(user.getUserId(), user.getDeptId(), user, null);
        String token = tokenService.createToken(loginUser);
        
        // 返回结果
        Map<String, Object> result = new HashMap<>();
        result.put(Constants.TOKEN, token);
        result.put("user", user);
        return AjaxResult.success(result);
    }
    
    /**
     * CAS登出
     */
    @GetMapping("/logout")
    public void logout(HttpServletRequest request, HttpServletResponse response) throws IOException
    {
        // 清除若依token
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (loginUser != null)
        {
            tokenService.delLoginUser(loginUser.getToken());
        }
        
        // 重定向到CAS登出页面
        String redirectUrl = casServerUrl + "/logout?service=" + request.getRequestURL().toString().replace("/logout", "/login");
        response.sendRedirect(redirectUrl);
    }
} 